package com.seaboxdata.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import org.apache.commons.dbutils.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Properties;

/**
 * @Author: dfjx
 * @Date: 2020/7/8 16:47
 * @Version 1.0
 * @Describe: 数据库连接工厂
 */
public class DataSourceConnectionFactory {
    private static Logger log = LoggerFactory.getLogger(DataSourceConnectionFactory.class);
    private static Connection dbConnection = null;
    private static DataSource dataSource = null;
    private  static Properties properties = new Properties();
    static {
        try {
            properties.load(new InputStreamReader(DataSourceConnectionFactory.class.getClassLoader().getResourceAsStream("db.properties"),"UTF-8"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            dbConnection = dataSource.getConnection();
        } catch (Exception e) {
            log.error("数据源初始化失败！错误信息：{}",e.getMessage());
        }
    }

    public static Connection getDbConnection(){
        Connection connection=null;
        try {
           String url= properties.getProperty("url");
           String user=properties.getProperty("username");
           String password=properties.getProperty("password");
           String driverClass=properties.getProperty("driverClassName");
           Class.forName(driverClass);
           connection=DriverManager.getConnection(url,user,password);
        }catch (ClassNotFoundException cfe){
            cfe.getStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeResource1(Connection conn, Statement ps, ResultSet rs){
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }

}
